import {
  Table,
  Image,
  Switch,
} from 'antd';
import React, { useMemo, useCallback, useState } from 'react';
import { postBannerItemFlagApi, deleteBannerItemApi } from '@/api/banner';
import DeleteButton from '../../../../../components/DeleteButton';

const BannerListTable = (props) => {
  const { data, refresh } = props
  // 改变访问状态
  const handleChangeItemFlag = useCallback(async (flag, bannerid) => {
    try {
      await postBannerItemFlagApi({ flag, bannerid })
      refresh()
    } catch (error) {
      console.log(error)
    }
  }, [])
  // 删除某个轮播图
  const handleDeleteItem = useCallback(async (bannerid) => {
    try {
      await deleteBannerItemApi({ bannerid })
      refresh()
    } catch (error) {
      console.log(error)
    }
  }, [])
  const [pageInfo, setPageInfo] = useState({ page: '1', pageSize: '5' })
  const handlePagesize = useCallback((page, pageSize) => {
    setPageInfo({ page, pageSize })
  }, [pageInfo])
  const columns = useMemo(() => (
    [
      {
        key: 'index',
        dataIndex: 'index',
        title: '序号',
        render: (_, record, index) => (pageInfo.page - 1) * pageInfo.pageSize + index + 1,
      },
      {
        key: 'img',
        dataIndex: 'img',
        title: '图片',
        render: (_) => {
          return (<Image width={150} src={_} />)
        },
      },
      {
        key: 'alt',
        title: 'alt',
        dataIndex: 'alt',
      },
      {
        key: 'link',
        title: 'link',
        dataIndex: 'link',
        render: (_) => <a>{ _ }</a>,
      },
      {
        key: 'flag',
        title: '访问状态',
        dataIndex: 'flag',
        render: (flag, record) => <Switch checked={flag} onChange={() => handleChangeItemFlag(!flag, record.bannerid)} />,
      },
      {
        key: 'del',
        title: 'del',
        render: (_, record) => <DeleteButton action={() => handleDeleteItem(record.bannerid)} />,
      },
    ]
  ), [data, pageInfo])
  return (
    <Table rowKey="bannerid" columns={columns} dataSource={data} pagination={{ pageSize: '5', onChange: handlePagesize }} />
    // 为什么 不返回函数 什么时候返回函数
  )
}
export default BannerListTable
